﻿/*
 * acest XML sitemap are facuta paginarea de 50k de linkuri cum cere standardul si implementeaza gzip pt a nu ajunge
 * la limita de 10MB, insa nu exista sitemap index implementat. Daca se trece de 50k de utilizatori trebuie pus manual un fisier
 * sitemap index si ca linkuri de sitemap-uri se dau in genul urmator:
 * map1.xml
 * map2.xml
 * map3.xml
 * ......
 * map<numar pagina>.xml
 * 
 * Prin mod_rewite numarul paginii ar trebui sa ajunga pana la urma ca parametru map.aspx?page=...
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ciripescu_WebRole.BL;
using Ciripescu_WebRole.Entities;
using System.IO;
using System.IO.Compression;

namespace Ciripescu_WebRole
{
    public partial class map : System.Web.UI.Page
    {
        public int NbPerPage = 49000;
        private const string DateFormat = @"yyyy-MM-dd";

        protected void Page_Load(object sender, EventArgs e)
        {
            int page = 1;
            try
            {
                if (Request.QueryString["page"] != null)
                    page = Convert.ToInt32(Request.QueryString["page"]);
            }
            catch (Exception)
            {
                // incercare de hacking - nu mai loghez - daca cineva a reusit sa treaca de filtrul cu expresii regulate si sa exploateze doar cu cifre
                // imi dau demisia :P
                return;
            }

            Response.Clear();            
            Response.ContentType = "text/xml";
            
            // compresie gzip ca sa incapa mai multe in limita de 10MB impusa de standard
            Response.AppendHeader("Content-Encoding", "gzip");
            Response.Filter = new System.IO.Compression.GZipStream(Response.Filter, CompressionMode.Compress);

            Response.Cache.SetExpires(new DateTime(1980, 11, 11));
            //Response.Cache.SetLastModified(DateTime.Parse("1/1/2001 00:00:01AM"));
            Response.Cache.SetNoStore();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetAllowResponseInBrowserHistory(false);

            StreamWriter sw = new StreamWriter(Response.OutputStream);
            sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sw.WriteLine("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");

            WriteLink(sw, "http://www.ciripescu.ro/all/");
            WriteLink(sw, "http://www.ciripescu.ro/despre/");
            WriteLink(sw, "http://www.ciripescu.ro/help/");            

            UserManager um = new UserManager();
            List<User> userList = um.GetAllItems().ToList();
            if (userList.Count > NbPerPage || page!=1) //trebuie paginat
            {
                // codul asta nu e testat - cu 2 useri nu are farmec sa faci paginare :P
                int start = (page - 1) * NbPerPage;
                int end = page * NbPerPage - 1;
                // pe ultima pagina vor fi mai putine elemente decat NbPerPage
                if (end > userList.Count-1) // -1 pt ca e index in array si incepe de la 0
                    end = userList.Count-1;
                if (end < start)
                {
                    // nu exista pagina?
                    // scoate totusi un xml valid si trimite un mail sa stiu!
                    string errormess = "In map.aspx " + Request.UserHostAddress + " a cerut o pagina care nu exista: " + page.ToString();
                    errormess += ". Avem in total " + userList.Count + " utilizatori!";
                    Utils.WriteLog(EventLogName.Error, errormess);
                    Utils.ReportCriticalError(errormess);                    
                    sw.WriteLine("</urlset>");
                    sw.Flush();
                    sw.Close();
                    Response.End();
                    return;
                }
                // aici la lungime ii +-1, la ora asta nu-mi dau seama si nici nu-mi pasa
                userList = userList.GetRange(start, end - start + 1);
            }
            
            foreach (User u in userList)
            {
                WriteLink(sw,"http://www.ciripescu.ro/u/"+u.GetUserName()+"/",u.LastCirip);
            }
            sw.WriteLine("</urlset>");
            sw.Flush();
            sw.Close();
            Response.End();
        }

        private void WriteLink(StreamWriter sw, string link, DateTime lastmod)
        {
            sw.WriteLine("<url>");
            sw.WriteLine("<loc>" + link + "</loc>");
            sw.WriteLine("<lastmod>" + lastmod.ToString(DateFormat) + "</lastmod>");
            sw.WriteLine("</url>");
        }
        private void WriteLink(StreamWriter sw, string link)
        {
            sw.WriteLine("<url>");
            sw.WriteLine("<loc>" + link + "</loc>");            
            sw.WriteLine("</url>");
        }
    }
}
